package com.industics.ibrain.npms;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import java.io.IOException;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

/**
 * Copyright with Industics company.
 * Author: KevinLi1130
 * Date: 12/05/2017
 * Time: 4:13 PM
 */
@Controller
public class QrCodeController {

    private final JdbcTemplate jdbcTemplate;

    @Autowired
    public QrCodeController(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    @GetMapping("/{qrCode}")
    public ResponseEntity redirectQrCode(@PathVariable String qrCode, HttpServletResponse response) throws IOException {
        Map<String, Object> qrCodeObj = jdbcTemplate.queryForMap("select id, short_code, url_pub, status from T_QR_CODE where short_code = '" + qrCode + "'");
        if (qrCodeObj.isEmpty()) {
            return ResponseEntity.ok("设备已经不存在！");
        }
        response.sendRedirect(qrCodeObj.get("url_pub").toString());
        return ResponseEntity.ok().build();
    }
}
